package org.osll.tictactoe.transport.corba;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import org.osll.tictactoe.Team;
import org.osll.tictactoe.engine.FieldImpl;
import org.osll.tictactoe.transport.corba.service.CurrentMove;
import org.osll.tictactoe.transport.corba.service.Move;
import org.osll.tictactoe.transport.corba.service.Size;


public class Adapter {
	
	public static String makeString(Object object) {
		try {
			ByteArrayOutputStream bs = new ByteArrayOutputStream();
			XMLEncoder xe = new XMLEncoder(bs);
			if(object != null)
				xe.writeObject(object);
			xe.close();
			String s = bs.toString();
	//		System.out.println(s);
			return s;
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static Object makeObject(String string) {
		try {
			ByteArrayInputStream bs = new ByteArrayInputStream(string.getBytes());
			XMLDecoder xd = new XMLDecoder(bs);
			Object obj = null;
			if(string.length()>0)
				obj = xd.readObject();
			xd.close();
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Team convertTeam(
			org.osll.tictactoe.transport.corba.service.Team team) {
		Team t = (Team)makeObject(team.description);
		return t;
	}

	public static CurrentMove convertCurrentMove(
			org.osll.tictactoe.CurrentMove currentMove) {
		CurrentMove cm = new CurrentMove();
		cm.description = makeString(currentMove);
		return cm;
	}

	public static Size convertSize(org.osll.tictactoe.Size size) {
		Size s = new Size();
		s.description = makeString(size);
		return s;
	}

	public static org.osll.tictactoe.Move convertMove(Move move) {
		return (org.osll.tictactoe.Move)makeObject(move.description);
	}

	public static Move convertMove(org.osll.tictactoe.Move lastMove) {
		Move m = new Move();
		m.description = makeString(lastMove);
		return m;
	}

	public static org.osll.tictactoe.transport.corba.service.Team convertTeam(
			Team team) {
		org.osll.tictactoe.transport.corba.service.Team t = new org.osll.tictactoe.transport.corba.service.Team();
		t.description = makeString(team);
		return t;
	}

	public static org.osll.tictactoe.CurrentMove convertCurrentMove(
			CurrentMove moveEndTime) {
		return (org.osll.tictactoe.CurrentMove) makeObject(moveEndTime.description);
	}

	public static org.osll.tictactoe.Size convertSize(Size size) {
		return (org.osll.tictactoe.Size) makeObject(size.description);
	}

	public static IllegalStateException getException(String description) {
		return (IllegalStateException)makeObject(description);
	}
}
